package com.starsea.book.ui.book.read.config

import android.content.DialogInterface
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.SeekBar
import androidx.core.view.get
import com.github.liuyueyi.quick.transfer.ChineseUtils
import com.github.liuyueyi.quick.transfer.constants.TransType
import com.jaredrummler.android.colorpicker.ColorPickerDialog
import com.starsea.book.R
import com.starsea.book.base.BaseDialogFragment
import com.starsea.book.base.adapter.ItemViewHolder
import com.starsea.book.base.adapter.RecyclerAdapter
import com.starsea.book.constant.EventBus
import com.starsea.book.constant.PreferKey
import com.starsea.book.data.entities.Book
import com.starsea.book.databinding.DialogReadBookStyleBinding
import com.starsea.book.databinding.ItemReadStyleBinding
import com.starsea.book.help.config.AppConfig
import com.starsea.book.help.config.ReadBookConfig
import com.starsea.book.lib.dialogs.selector
import com.starsea.book.lib.theme.accentColor
import com.starsea.book.lib.theme.bottomBackground
import com.starsea.book.lib.theme.buttonDisabledColor
import com.starsea.book.lib.theme.getPrimaryTextColor
import com.starsea.book.lib.theme.getSecondaryTextColor
import com.starsea.book.model.ReadBook
import com.starsea.book.ui.book.read.ReadBookActivity
import com.starsea.book.ui.font.FontSelectDialog
import com.starsea.book.ui.widget.seekbar.SeekBarChangeListener
import com.starsea.book.utils.*
import com.starsea.book.utils.viewbindingdelegate.viewBinding
import splitties.views.onLongClick

class ReadStyleDialog() : BaseDialogFragment(R.layout.dialog_read_book_style),
    FontSelectDialog.CallBack {

    private val binding by viewBinding(DialogReadBookStyleBinding::bind)
    private val callBack get() = activity as? ReadBookActivity

    /**
     * 设置字体/背景颜色
     */
    private lateinit var styleAdapter: StyleAdapter
    private var secondaryTextColor = 0
    private val adapter by lazy { BgAdapter(requireContext(), secondaryTextColor) }

    override fun onStart() {
        super.onStart()
        dialog?.window?.run {
            clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
            setBackgroundDrawableResource(R.color.background)
            decorView.setPadding(0, 0, 0, 0)
            val attr = attributes
            attr.dimAmount = 0.0f
            attr.gravity = Gravity.BOTTOM
            attributes = attr
            setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        }
    }

    override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) {
        (activity as ReadBookActivity).bottomDialog++
        initView()
        initData()
        initViewEvent()
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        ReadBookConfig.save()
        (activity as ReadBookActivity).bottomDialog--
    }

    private fun initView() = binding.run {
        val bg = requireContext().bottomBackground
        val isLight = ColorUtils.isColorLight(bg)
        val textColor = requireContext().getPrimaryTextColor(isLight)
        secondaryTextColor = requireContext().getSecondaryTextColor(isLight)
        rootView.setBackgroundColor(bg)
        tvPageAnim.setTextColor(textColor)
        tvBgTs.setTextColor(textColor)
        tvShareLayout.setTextColor(textColor)

        upBrightnessState()
//        dsbTextSize.valueFormat = {
//            (it + 5).toString()
//        }

//        tvTextsize.text =
//            (it + 5).toString()
//

        dsbTextLetterSpacing.valueFormat = {
            ((it - 50) / 100f).toString()
        }
        dsbLineSize.valueFormat = { ((it - 10) / 10f).toString() }
        dsbParagraphSpacing.valueFormat = { (it / 10f).toString() }
//        styleAdapter = StyleAdapter()
        rvStyle.adapter = adapter
//        styleAdapter.addFooterView {
//            ItemReadStyleBinding.inflate(layoutInflater, it, false).apply {
//                ivStyle.setPadding(6.dpToPx(), 6.dpToPx(), 6.dpToPx(), 6.dpToPx())
//                ivStyle.setText(null)
//                ivStyle.setColorFilter(textColor)
//                ivStyle.borderColor = textColor
//                ivStyle.setImageResource(R.drawable.ic_add)
//                root.setOnClickListener {
//                    ReadBookConfig.configList.add(ReadBookConfig.Config())
//                    showBgTextConfig(ReadBookConfig.configList.lastIndex)
//                }
//            }
//        }

        seekBrightness.post {
            seekBrightness.progress = AppConfig.readBrightness
        }

    }

    private fun initData() {
        binding.cbShareLayout.isChecked = ReadBookConfig.shareLayout
        upView()
//        styleAdapter.setItems(ReadBookConfig.configList)

        requireContext().assets.list("bg")?.let {
            adapter.setItems(it.toList())
        }
    }

    private fun initViewEvent() = binding.run {
        chineseConverter.onChanged {
            ChineseUtils.unLoad(*TransType.values())
            postEvent(EventBus.UP_CONFIG, true)
        }
        textFontWeightConverter.onChanged {
            postEvent(EventBus.UP_CONFIG, true)
        }
        tvTextFont.setOnClickListener {
            showDialogFragment<FontSelectDialog>()
        }
        tvTextIndent.setOnClickListener {
            context?.selector(
                title = getString(R.string.text_indent),
                items = resources.getStringArray(R.array.indent).toList()
            ) { _, index ->
                ReadBookConfig.paragraphIndent = "　".repeat(index)
                postEvent(EventBus.UP_CONFIG, true)
            }
        }
        tvPadding.setOnClickListener {
            dismissAllowingStateLoss()
            callBack?.showPaddingConfig()
        }
        tvTip.setOnClickListener {
            TipConfigDialog().show(childFragmentManager, "tipConfigDialog")
        }
        rgPageAnim.setOnCheckedChangeListener { _, checkedId ->
            ReadBook.book?.setPageAnim(null)
            ReadBookConfig.pageAnim = binding.rgPageAnim.getIndexById(checkedId)
            callBack?.upPageAnim()
            ReadBook.loadContent(false)
        }
        cbShareLayout.onCheckedChangeListener = { _, isChecked ->
            ReadBookConfig.shareLayout = isChecked
            upView()
            postEvent(EventBus.UP_CONFIG, true)
        }
//        dsbTextSize.onChanged = {
//            ReadBookConfig.textSize = it + 5
//            postEvent(EventBus.UP_CONFIG, true)
//        }

        //亮度跟随
        ivBrightnessAuto.setOnClickListener {
            requireContext().putPrefBoolean("brightnessAuto", !brightnessAuto())
            upBrightnessState()
        }
        //亮度调节
        seekBrightness.setOnSeekBarChangeListener(object : SeekBarChangeListener {

            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    setScreenBrightness(progress.toFloat())
                }
            }

            override fun onStopTrackingTouch(seekBar: SeekBar) {
                AppConfig.readBrightness = seekBar.progress
            }

        })

        rflMinFontSize.setOnClickListener {

            if (ReadBookConfig.textSize <= 5) {
                return@setOnClickListener
            }

            ReadBookConfig.textSize--
            tvTextsize.text =
                (ReadBookConfig.textSize).toString()
            postEvent(EventBus.UP_CONFIG, true)

        }

        rflPlusFontSize.setOnClickListener {
            if (ReadBookConfig.textSize >= 50) {
                return@setOnClickListener
            }

            ReadBookConfig.textSize++
            tvTextsize.text =
                (ReadBookConfig.textSize).toString()
            postEvent(EventBus.UP_CONFIG, true)
        }


        dsbTextLetterSpacing.onChanged = {
            ReadBookConfig.letterSpacing = (it - 50) / 100f
            postEvent(EventBus.UP_CONFIG, true)
        }
        dsbLineSize.onChanged = {
            ReadBookConfig.lineSpacingExtra = it
            postEvent(EventBus.UP_CONFIG, true)
        }
        dsbParagraphSpacing.onChanged = {
            ReadBookConfig.paragraphSpacing = it
            postEvent(EventBus.UP_CONFIG, true)
        }

        tvTextColor.setOnClickListener {
            ColorPickerDialog.newBuilder()
                .setColor(curTextColor())
                .setShowAlphaSlider(false)
                .setDialogType(ColorPickerDialog.TYPE_CUSTOM)
                .setDialogId(BgTextConfigDialog.TEXT_COLOR)
                .show(requireActivity())
        }


        rtvColorOne.setOnClickListener {
            ReadBookConfig.durConfig.setCurBg(0, "#D6D2DC")
            postEvent(EventBus.UP_CONFIG, false)
        }
        rtvColorTwo.setOnClickListener {
            ReadBookConfig.durConfig.setCurBg(0, "#ffffff")
            postEvent(EventBus.UP_CONFIG, false)
        }
        rtvColorThree.setOnClickListener {
            ReadBookConfig.durConfig.setCurBg(0, "#D3E1D0")
            postEvent(EventBus.UP_CONFIG, false)
        }
        rtvColorFour.setOnClickListener {
            ReadBookConfig.durConfig.setCurBg(0, "#CCD3E3")
            postEvent(EventBus.UP_CONFIG, false)
        }
        rtvColorFive.setOnClickListener {
            ReadBookConfig.durConfig.setCurBg(0, "#F1D9AF")
            postEvent(EventBus.UP_CONFIG, false)
        }

        rbLineSpacing1.setOnClickListener {
            ReadBookConfig.lineSpacingExtra = 8
            postEvent(EventBus.UP_CONFIG, true)
        }
        rbLineSpacing2.setOnClickListener {
            ReadBookConfig.lineSpacingExtra = 9
            postEvent(EventBus.UP_CONFIG, true)
        }
        rbLineSpacing3.setOnClickListener {
            ReadBookConfig.lineSpacingExtra = 12
            postEvent(EventBus.UP_CONFIG, true)
        }
        rbLineSpacing4.setOnClickListener {
            ReadBookConfig.lineSpacingExtra = 14
            postEvent(EventBus.UP_CONFIG, true)
        }


    }

    private var textColorNight: String = "#ADADAD"//夜间文字颜色
    private var textColorEInk: String = "#000000"
    val textColor: Int get() = ReadBookConfig.durConfig.curTextColor()
    fun curTextColor(): Int {
        return when {
            AppConfig.isEInkMode -> Color.parseColor(textColorEInk)
            AppConfig.isNightTheme -> Color.parseColor(textColorNight)
            else -> Color.parseColor("#3E3D3B")
        }
    }

    private fun changeBg(index: Int) {
        val oldIndex = ReadBookConfig.styleSelect
        if (index != oldIndex) {
            ReadBookConfig.styleSelect = index
            upView()
//            styleAdapter.notifyItemChanged(oldIndex)
//            styleAdapter.notifyItemChanged(index)
            postEvent(EventBus.UP_CONFIG, true)
        }
    }

    private fun showBgTextConfig(index: Int): Boolean {
        dismissAllowingStateLoss()
        changeBg(index)
        callBack?.showBgTextConfig()
        return true
    }

    private fun upView() = binding.run {
        textFontWeightConverter.upUi(ReadBookConfig.textBold)
        ReadBook.pageAnim().let {
            if (it >= 0 && it < rgPageAnim.childCount) {
                rgPageAnim.check(rgPageAnim[it].id)
            }
        }
        ReadBookConfig.let {

            tvTextsize.text =
                (it.textSize).toString()

//            dsbTextSize.progress = it.textSize - 5
            dsbTextLetterSpacing.progress = (it.letterSpacing * 100).toInt() + 50
            dsbLineSize.progress = it.lineSpacingExtra
            dsbParagraphSpacing.progress = it.paragraphSpacing
        }
    }

    override val curFontPath: String
        get() = ReadBookConfig.textFont

    override fun selectFont(path: String) {
        if (path != ReadBookConfig.textFont) {
            ReadBookConfig.textFont = path
            postEvent(EventBus.UP_CONFIG, true)
        }
    }

    inner class StyleAdapter :
        RecyclerAdapter<ReadBookConfig.Config, ItemReadStyleBinding>(requireContext()) {

        override fun getViewBinding(parent: ViewGroup): ItemReadStyleBinding {
            return ItemReadStyleBinding.inflate(inflater, parent, false)
        }

        override fun convert(
            holder: ItemViewHolder,
            binding: ItemReadStyleBinding,
            item: ReadBookConfig.Config,
            payloads: MutableList<Any>
        ) {
            binding.apply {
                ivStyle.setText(item.name.ifBlank { "文字" })
                ivStyle.setTextColor(item.curTextColor())
                ivStyle.setImageDrawable(item.curBgDrawable(100, 150))
                if (ReadBookConfig.styleSelect == holder.layoutPosition) {
                    ivStyle.borderColor = accentColor
                    ivStyle.setTextBold(true)
                } else {
                    ivStyle.borderColor = item.curTextColor()
                    ivStyle.setTextBold(false)
                }
            }
        }

        override fun registerListener(holder: ItemViewHolder, binding: ItemReadStyleBinding) {
            binding.apply {
                ivStyle.setOnClickListener {
                    if (ivStyle.isInView) {
                        changeBg(holder.layoutPosition)
                    }
                }
                ivStyle.onLongClick(ivStyle.isInView) {
                    if (ivStyle.isInView) {
                        showBgTextConfig(holder.layoutPosition)
                    }
                }
            }
        }

    }

    private val showBrightnessView
        get() = requireContext().getPrefBoolean(
            PreferKey.showBrightnessView,
            true
        )

    private fun brightnessAuto(): Boolean {
        return requireContext().getPrefBoolean("brightnessAuto", true) || !showBrightnessView
    }

    fun upBrightnessState() {
        if (brightnessAuto()) {
//            binding.ivBrightnessAuto.setColorFilter(requireContext().accentColor)
            binding.ivBrightnessAuto.setImageResource(R.mipmap.icon_pwd_hide)
            binding.seekBrightness.isEnabled = false
        } else {
            binding.ivBrightnessAuto.setImageResource(R.mipmap.icon_pwd_hide)
//            binding.ivBrightnessAuto.setColorFilter(requireContext().buttonDisabledColor)
            binding.seekBrightness.isEnabled = true
        }
        setScreenBrightness(AppConfig.readBrightness.toFloat())
    }

    /**
     * 设置屏幕亮度
     */
    fun setScreenBrightness(value: Float) {
        activity?.run {
            var brightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE
            if (!brightnessAuto() && value != WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE) {
                brightness = value
                if (brightness < 1f) brightness = 1f
                brightness /= 255f
            }
            val params = window.attributes
            params.screenBrightness = brightness
            window.attributes = params
        }
    }
}